<template>
  <view class="my-moments-page">
    <!-- 头部区域 -->
    <header class="header-top">
      <image v-if="hasCover" class="header-bg-image" :src="headerBgImage" mode="aspectFill"></image>
      <view v-else class="header-bg-placeholder">
        <text class="placeholder-text">暂无背景</text>
      </view>
      <view class="back-button" @click="goBack">
        <image class="back-icon" src="/static/back-icon.png" mode="aspectFit"></image>
      </view>
      <view class="edit-bg-button" @click="editBackground">
        <image class="edit-icon" src="/static/edit.png" mode="aspectFit"></image>
        <text class="edit-text">编辑背景</text>
      </view>
    </header>

    <!-- 朋友圈动态列表 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      @scrolltolower="onScrollToLower"
      lower-threshold="100"
      enable-back-to-top
    >
      <view class="content">
        <view 
          v-for="(item, index) in momentsList" 
          :key="item.id || index" 
          class="moment-item"
          @click="goToDetail(item.id)"
        >
          <!-- 日期和状态 -->
          <view class="moment-header">
            <text class="moment-date">{{ formatDate(item.publishTime) }}</text>
            <view class="status-tag" :class="getStatusClass(item.status)">
              <text>{{ getStatusText(item.status) }}</text>
            </view>
          </view>

          <!-- 文本内容 -->
          <view v-if="item.content" class="moment-content">
            <text>{{ item.content }}</text>
          </view>

          <!-- 媒体内容 -->
          <view class="moment-media">
            <!-- 视频 -->
            <view v-if="item.video && item.video.length > 0" class="video-container">
              <view class="video-thumbnail" v-for="(video, vIndex) in item.video" :key="vIndex">
                <video :src="video" :poster="getVideoPoster(item, vIndex)" controls></video>
                <view class="video-overlay" v-if="item.videoTitle">
                  <text class="video-title">{{ item.videoTitle }}</text>
                  <text class="video-subtitle" v-if="item.videoSubtitle">{{ item.videoSubtitle }}</text>
                </view>
              </view>
            </view>

            <!-- 图片网格 -->
            <view v-else-if="item.images && item.images.length > 0" class="image-grid" :class="getImageGridClass(item.images.length)">
              <image 
                v-for="(img, imgIndex) in item.images" 
                :key="imgIndex"
                :src="img" 
                mode="aspectFill"
                class="moment-image"
                @click.stop="previewImage(item.images, imgIndex)"
              ></image>
            </view>
          </view>

          <!-- 互动数据 -->
          <view class="moment-interactions">
            <view class="interaction-item">
              <image class="interaction-icon" src="/static/star.png" mode="aspectFit"></image>
              <text class="interaction-count">{{ item.favoriteCount || 0 }}</text>
            </view>
            <view class="interaction-item">
              <image class="interaction-icon" src="/static/comment.png" mode="aspectFit"></image>
              <text class="interaction-count">{{ item.commentCount || 0 }}</text>
            </view>
            <view class="interaction-item">
              <image class="interaction-icon" src="/static/like.png" mode="aspectFit"></image>
              <text class="interaction-count">{{ item.likeCount || 0 }}</text>
            </view>
            <view class="interaction-item">
              <image class="interaction-icon" src="/static/share.png" mode="aspectFit"></image>
              <text class="interaction-count">{{ item.shareCount || 0 }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="moment-actions" @click.stop>
            <view class="action-btn delete-btn" @click="handleDelete(item)">
              <text>删除</text>
            </view>
            <view class="action-btn edit-btn" @click="handleEdit(item)">
              <text>编辑</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="total > 0 && total > momentsList.length" class="load-more" @click="loadMore">
          加载更多
        </view>
        <view v-else-if="momentsList && momentsList.length > 0" class="no-more-data">
          没有更多数据了
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
// import CommunityUtil from '@/sheep/api/index/community'
import UserApi from '@/sheep/api/member/user'
import FileApi from '@/sheep/api/infra/file'
import userStore from '@/sheep/store/user'

// 头部背景图片
const headerBgImage = ref('/static/header-bg.png')
const hasCover = ref(false) // 是否有封面图片

// 朋友圈动态列表
const momentsList = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 获取用户信息并设置封面图片
const loadUserCover = async () => {
  try {
    const res = await UserApi.getUserInfo()
    if (res && res.code === 0 && res.data) {
      const momentsCover = res.data.momentsCover
      if (momentsCover) {
        headerBgImage.value = momentsCover
        hasCover.value = true
      } else {
        hasCover.value = false
      }
    } else {
      hasCover.value = false
    }
  } catch (error) {
    console.error('获取用户封面失败:', error)
    hasCover.value = false
  }
}

// 编辑背景
const editBackground = async () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      
      try {
        // 先上传图片
        uni.showLoading({ title: '上传中...' })
        const uploadRes = await FileApi.uploadFile(tempFilePath, 'user-cover')
        
        // uploadFile 返回格式可能是 { data: 'url' } 或 { code: 0, data: 'url' }
        let imageUrl = null
        if (uploadRes) {
          if (uploadRes.data) {
            // 如果是字符串，直接使用；如果是对象，取 url 字段
            imageUrl = typeof uploadRes.data === 'string' ? uploadRes.data : (uploadRes.data.url || uploadRes.data)
          } else if (uploadRes.error === 1) {
            // 上传失败
            uni.showToast({
              title: uploadRes.msg || '上传失败',
              icon: 'none'
            })
            return
          }
        }
        
        if (!imageUrl) {
          uni.showToast({
            title: '上传失败，未获取到图片地址',
            icon: 'none'
          })
          return
        }
        
        // 调用更新封面接口
        const updateRes = await UserApi.updateCover({ momentsCover: imageUrl })
        
        if (updateRes && updateRes.code === 0) {
          // 更新本地封面显示
          headerBgImage.value = imageUrl
          hasCover.value = true
          uni.showToast({
            title: '封面更新成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: updateRes?.msg || '更新失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('更新封面失败:', error)
        uni.showToast({
          title: '更新失败，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    fail: (error) => {
      console.error('选择图片失败:', error)
    }
  })
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取状态标签类名
const getStatusClass = (status) => {
  // status: 0-待审核, 1-已通过, 2-已驳回
  if (status === 1) return 'status-approved'
  if (status === 2) return 'status-rejected'
  return 'status-pending'
}

// 获取状态文本
const getStatusText = (status) => {
  if (status === 1) return '已通过'
  if (status === 2) return '已驳回'
  return '待审核'
}

// 获取图片网格布局类名
const getImageGridClass = (count) => {
  if (count === 1) return 'grid-single'
  if (count === 2) return 'grid-double'
  if (count === 3) return 'grid-triple'
  if (count === 4) return 'grid-quad'
  if (count <= 6) return 'grid-six'
  return 'grid-nine'
}

// 预览图片
const previewImage = (images, currentIndex) => {
  uni.previewImage({
    urls: images,
    current: currentIndex
  })
}

// 获取视频封面
const getVideoPoster = (item, index) => {
  // 如果有封面图，返回封面图，否则返回第一张图片
  if (item.videoPoster) return item.videoPoster
  if (item.images && item.images.length > 0) return item.images[0]
  return ''
}

// 获取我的朋友圈动态列表
const getMyMomentsList = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    // 检查登录状态
    const store = userStore()
    if (!store.isLogin) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      loading.value = false
      return
    }
    
    // 如果用户信息中没有 id，先获取用户信息
    if (!store.userInfo?.id) {
      await store.getInfo()
    }
    
    const userId = store.userInfo?.id
    if (!userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      loading.value = false
      return
    }

    const CommunityUtil = (await import('@/sheep/api/index/community')).default
    const res = await CommunityUtil.getCommunityList({
      userId: userId,
      page: page.value,
      pageSize: pageSize.value
    })

    const listData = res.data?.list || []
    const totalData = res.data?.total || 0

    if (page.value === 1) {
      momentsList.value = listData
    } else {
      momentsList.value = [...momentsList.value, ...listData]
    }
    total.value = totalData

    // 处理图片和视频数据
    momentsList.value.forEach(item => {
      if (item.images && typeof item.images === 'string') {
        item.images = item.images.split(',').filter(img => img)
      }
      if (item.video && typeof item.video === 'string') {
        item.video = item.video.split(',').filter(v => v)
      }
    })
  } catch (error) {
    console.error('获取我的朋友圈失败:', error)
    uni.showToast({
      title: '获取失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (total.value > 0 && momentsList.value.length >= total.value) {
    return
  }
  if (loading.value) {
    return
  }
  page.value++
  getMyMomentsList()
}

// 滚动到底部
const onScrollToLower = () => {
  loadMore()
}

// 跳转到动态详情页
const goToDetail = (id) => {
  if (!id) return
  uni.navigateTo({
    url: `/pages/dynamic/detail?id=${id}`
  })
}

// 删除动态
const handleDelete = async (item) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条动态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const CommunityUtil = (await import('@/sheep/api/index/community')).default
          const deleteRes = await CommunityUtil.deleteCommunity({ id: item.id })
          if (deleteRes && deleteRes.code === 0) {
            // 删除成功，从列表中移除
            const index = momentsList.value.findIndex(m => m.id === item.id)
            if (index > -1) {
              momentsList.value.splice(index, 1)
              total.value--
            }
          }
        } catch (error) {
          console.error('删除动态失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 编辑动态
const handleEdit = (item) => {
  uni.navigateTo({
    url: `/pages/post/post?editId=${item.id}`
  })
}

// 刷新数据
const refreshData = async () => {
  page.value = 1
  momentsList.value = []
  await getMyMomentsList()
}

// 下拉刷新
onPullDownRefresh(async () => {
  await refreshData()
  uni.stopPullDownRefresh()
})

onMounted(async () => {
  // 检查登录状态
  const store = userStore()
  if (!store.isLogin) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }
  
  // 如果用户信息中没有 id，先获取用户信息
  if (!store.userInfo?.id) {
    await store.getInfo()
  }
  
  loadUserCover()
  getMyMomentsList()
})

onShow(() => {
  // 页面显示时刷新封面（如果从其他页面返回）
  loadUserCover()
})
</script>

<style lang="scss" scoped>
.my-moments-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.header-top {
  position: relative;
  height: 500rpx;
  overflow: hidden;
  z-index: 0;
}

.header-bg-image {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.header-bg-placeholder {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
  z-index: -1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-text {
  font-size: 32rpx;
  color: #999;
}

.back-button {
  position: absolute;
  left: 10rpx;
  top: 50rpx;
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.back-icon {
  width: 150rpx;
  height: 150rpx;
}

.edit-bg-button {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
  padding: 20rpx;
}

.edit-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.edit-text {
  font-size: 24rpx;
  color: #fff;
}

.content-scroll {
  flex: 1;
  height: 0;
  background-color: transparent;
  position: relative;
  z-index: 10;
}

.content {
  padding: 20rpx 17rpx;
  margin-top: -100rpx;
  position: relative;
  z-index: 10;
  background-color: transparent;
}

.moment-item {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.moment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.moment-date {
  font-size: 28rpx;
  color: #666;
}

.status-tag {
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  
  &.status-approved {
    background-color: #e3f2fd;
    color: #1976d2;
  }
  
  &.status-rejected {
    background-color: #ffebee;
    color: #d32f2f;
  }
  
  &.status-pending {
    background-color: #fff3e0;
    color: #f57c00;
  }
}

.moment-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.moment-media {
  margin-bottom: 20rpx;
}

.video-container {
  width: 100%;
}

.video-thumbnail {
  position: relative;
  width: 100%;
  border-radius: 10rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
  
  video {
    width: 100%;
    height: 400rpx;
  }
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3);
  padding: 20rpx;
}

.video-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  text-align: center;
}

.video-subtitle {
  color: #fff;
  font-size: 24rpx;
  text-align: center;
}

.image-grid {
  display: grid;
  gap: 10rpx;
  
  &.grid-single {
    grid-template-columns: 1fr;
    .moment-image {
      width: 100%;
      height: 400rpx;
    }
  }
  
  &.grid-double {
    grid-template-columns: 1fr 1fr;
    .moment-image {
      width: 100%;
      height: 200rpx;
    }
  }
  
  &.grid-triple {
    grid-template-columns: 1fr 1fr 1fr;
    .moment-image {
      width: 100%;
      height: 200rpx;
    }
  }
  
  &.grid-quad {
    grid-template-columns: 1fr 1fr;
    .moment-image {
      width: 100%;
      height: 200rpx;
    }
  }
  
  &.grid-six {
    grid-template-columns: 1fr 1fr 1fr;
    .moment-image {
      width: 100%;
      height: 200rpx;
    }
  }
  
  &.grid-nine {
    grid-template-columns: 1fr 1fr 1fr;
    .moment-image {
      width: 100%;
      height: 200rpx;
    }
  }
}

.moment-image {
  border-radius: 10rpx;
  width: 100%;
}

.moment-interactions {
  display: flex;
  justify-content: flex-end;
  gap: 40rpx;
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;
}

.interaction-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.interaction-icon {
  width: 32rpx;
  height: 32rpx;
}

.interaction-count {
  font-size: 24rpx;
  color: #666;
}

.moment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  width: 150rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 56rpx;
  font-size: 28rpx;
  
  &.delete-btn {
    background-color: #f5f5f5;
    color: #666;
  }
  
  &.edit-btn {
    background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
    color: #fff;
  }
}

.load-more, .no-more-data {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 24rpx;
}
</style>

